// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const send = require('../requestReturn')
const db = uniCloud.database();

// 创建唯一 code
const generateUniqueCode = () => {
	const timestamp = Date.now(); // 当前时间戳
	const randomNum = Math.floor(Math.random() * 1000); // 随机数
	return `${timestamp}-${randomNum}`;
};

// 获取用户信息
const getUserInfo = async (openid) => {
	// 从 user 库中，查找当前用户信息
	const {
		data
	} = await db.collection('user').where({
		userID: openid,
	}).get()
	if (data) {
		return data[0]
	} else {
		return send(null, '查无此人,是个黑户!', -1)
	}
}

// 获取用户头像
const getUserAvatarURL = async (avatarID) => {
	const {
		fileList
	} = await uniCloud.getTempFileURL({
		fileList: [avatarID]
	})
	if (fileList) {
		return fileList[0].tempFileURL
	} else {
		return send('', '没有头像,没有情头!', -1)
	}
}

// 获取房间信息
const getRoomInfo = async (roomCode) => {
	// 通过 roomCode 获取房间信息
	const {
		data
	} = await db.collection('room').where({
		roomCode
	}).get()
	if (data) {
		return data[0]
	} else {
		return send(null, '要不先开个房?(正经的)', -1)
	}
}

module.exports = {
	_before: function() {},
	
	// 获取房间信息
	getRoomInfo,

	// 创建房间
	creatRoom: async function(openid) {
		const roomCode = generateUniqueCode()

		const userInfo = await getUserInfo(openid)

		const avatarURL = await getUserAvatarURL(userInfo.avatarID)

		// 将用户信息加入到房间成员 users 中，并在 room 库中新增当前数据
		if (userInfo) {
			const result = {
				roomCode,
				users: [{
					userID: userInfo.userID,
					name: userInfo.name,
					avatarURL,
					integral: 0
				}]
			}
			const res = await db.collection('room').add(result)
			// 返回结果
			return send(result)
		} else {
			return send(null, '出错了,联系开发帅哥解决一下~', -1)
		}

	},

	// 加入/重连房间
	joinRoom: async function(openid, roomCode) {
		const roomInfo = await getRoomInfo(roomCode)
		if (roomInfo) {
			const userInfo = await getUserInfo(openid)
			const findUser = roomInfo.users.findIndex(item => item.userID === userInfo.userID)
			if (findUser === -1) {
				const avatarURL = await getUserAvatarURL(userInfo.avatarID)
				const user = {
					userID: userInfo.userID,
					name: userInfo.name,
					avatarURL,
					integral: 0
				}
				roomInfo.users.push(user)
				const res = await db.collection('room').where({
					roomCode
				}).update(roomInfo)
				if (res.updated === 1) {
					return send(roomInfo)
				} else {
					return send(null, '加入失败!', -2)
				}
			} else {
				return send(roomInfo)
			}
		} else {
			return send(null, '加入失败，房间不存在!', -1)
		}
	},

	// 离开房间
	leaveRoom: async function(openid, roomCode) {
		let result = null
		const roomInfo = await getRoomInfo(roomCode)
		if (roomInfo) {
			roomInfo.users = roomInfo.users.filter(item => item.userID !== openid)
			let res;
			if (roomInfo.users.length) {
				res = await db.collection('room').where({
					roomCode
				}).update(roomInfo)
			} else {
				res = await db.collection('room').where({
					roomCode
				}).remove()
			}
			return send(roomInfo)
		} else {
			return send(null, '网络故障，请稍后重试!', -1)
		}
	},
}